package com.huamoxi.controller;

import com.huamoxi.consts.ResponseConst;
import com.huamoxi.result.Result;
import com.huamoxi.service.SysFileService;
import com.huamoxi.utils.JwtUtil;
import com.huamoxi.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private SysFileService sysFileService;

    @PostMapping("/upload")
    public Result upload(MultipartFile[] files, HttpServletRequest request) {
        if (files == null || files.length == 0) {
            return ResultUtil.fail("参数错误");
        }
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            return ResultUtil.fail("请先登录");
        } else {
            // 如果携带了正确格式的token要先得到token
            String token = header.replace("Bearer ", "");
            try {
                Claims claims = jwtUtil.verifyToken(token);

                if ("1".equals(claims.get("status").toString())) {
                    return ResultUtil.fail("上传失败, 账号已被锁定");
                }

                Long userId = Long.parseLong(claims.get("id").toString());
                return sysFileService.upload(files, userId);
            } catch (Exception e) {
                if (e instanceof JwtException) {
                    return ResultUtil.fail(ResponseConst.ERR_LOGIN_EXP_TOKEN);
                } else {
                    return ResultUtil.fail("请先登录");
                }
            }
        }
    }
}
